# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
from itertools import count
from typing import Optional
from Data_Structure.linkList import ListNode

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        start = ListNode(0)
        start.next = head
        left = start
        right = head
        if n == 1: #删除最后一个节点
            while right.next :#如果没找到最后一个节点
                right = right.next #向后移一位
                left = left.next #指针后移一位
            left.next = None
            return start.next
        else :
            count = 0
            while left.next: #统计链表长度
                count += 1
                left = left.next
            left = start #重置left
            if n == count:#删除第一个节点
                return head.next
            idx = 0 #当前节点的位置
            while idx != count-n:#5  2  0 1 2 3 4 5
                idx += 1
                left = left.next
            left.next = left.next.next #跳过倒数第n个节点
            return start.next
